import http from '@/common/request';
import publicFc from '@/common/publicFc';
// #ifndef VUE3
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//获取会话数据的页码
let getConversationDatasPage = 0
const store = new Vuex.Store({
// #endif

// #ifdef VUE3
import { createStore } from 'vuex'
  const store = createStore({
// #endif
	state: {
		watermark:'',//背景水印
		userInfo:'',
		chatlist:{},
		chatDatalist:{},
		chatListNum:0,
		chatDataState:1,
		chatDataUserId:'',
		topicReply:{},
		topicRed:{},
		friendApply:{},
		chatCheckedShow: false,
		chat_msg_list: {},
		navigatorType: 1,	//导航方式 1 底部导航 2 头部导航
		navToolShowMy: 1,	//如果导航方式是 头部导航，点击右上角+号时，是否有个人中心选项
	},
	mutations: {
		update_UserInfo(state, data) {//个人信息
			state.userInfo = typeof data=='object'?data:JSON.parse(data)
		},
		clear_Userinfo(state){
			state.userInfo = '';
		},
		update_ChatList(state, data) {
			state.chatlist = data
		},
		update_chatDatalist(state, data) {
			state.chatDatalist = data
		},
		update_topicReply(state, data) {
			state.topicReply = data
			uni.setStorageSync('topicReply', JSON.stringify(data));
		},
		update_topicRed(state, data) {
			state.topicRed = data
			uni.setStorageSync('topicRed', JSON.stringify(data));
		},
		update_friendApply(state, data) {
			state.friendApply = data
			uni.setStorageSync('friendApply', JSON.stringify(data));
		}
	},
	actions: {
		updateChatDataState(context,data){
			context.state.chatDataState++
			context.state.chatDataUserId=data
		},
		tabBarpull(context){
			context.dispatch('get_UserInfo').then(res=>{
				context.dispatch('getChatList')
				// 朋友圈新消息
				var topicReply=publicFc.getKeyObjectStorage('topicReply')
				context.state.topicReply=topicReply
				// 新朋友圈
				var topicRed=publicFc.getKeyObjectStorage('topicRed')
				context.state.topicRed=topicRed
				// 新朋友
				var friendApply=publicFc.getKeyObjectStorage('friendApply')
				context.state.friendApply=friendApply
				var chatListNum=context.state.chatListNum ? context.state.chatListNum : 0
				var topicReplyCount=topicReply.count ? topicReply.count : 0
				var friendApplyCount=friendApply.count ? friendApply.count : 0
				var sumCount=chatListNum+topicReplyCount+friendApplyCount
				// #ifdef APP-PLUS
				plus.runtime.setBadgeNumber(sumCount);
				// #endif
			})
		},
		get_UserInfo (context) {
			return new Promise((resolve, reject) => {
			     var cacheuserinfo = context.state.userInfo;
			    if(cacheuserinfo){
			         cacheuserinfo = JSON.stringify(cacheuserinfo);
		             context.commit('update_UserInfo',cacheuserinfo)
		             resolve(cacheuserinfo);
			    }else{
			         var token = uni.getStorageSync('Authorization');
                     if(token){
                        http.request({
        					url: '/my/getInfo',
        					success: (res) => {
        						if (res.data.code == 200) {
        							context.commit('update_UserInfo',res.data.data)
        							resolve(res.data.data)
        						}else{
        							reject(res.data)
        						}
        					},
        					fail: (error) => {
        						reject(error)
        					}
        				});
                     }else{
                        reject(false)
                     }
			    }
			})
		},
		getchatDatalist(context,getKey) {//获取聊天数据列表
            if(getKey){
                var data = context.state.chatDatalist;
                if(!data[getKey]){
                    data[getKey] = {id:getKey,list:[]};
                }
                context.commit('update_chatDatalist',data);
            }
		},
        getGroupNameData(context){
			return publicFc.getKeyObjectStorage(context.state.userInfo.userId+'_'+'GroupNameData');
        },
        addGroupNameData(context,data){
            var obj=context.dispatch('getChatData');if(!obj)obj={};
            obj[data.id]=data.data;
            uni.setStorageSync(context.state.userInfo.userId+'_'+'GroupNameData', JSON.stringify(obj));
        },
        getChatData(context){
			return publicFc.getKeyObjectStorage(context.state.userInfo.userId+'_'+'chatData');
        },
        updateChatData(context,data){
            uni.setStorageSync(context.state.userInfo.userId+'_'+'chatData', JSON.stringify(data));
        },
		updateConversation(context, [id, data, cover = false]) {
			let conversationDatas = context.state.chatDatalist
			let conversation = conversationDatas[id] || {}
			conversationDatas[id] = Object.assign(cover ? {} : conversation, data)
			context.state.chatDatalist = Object.assign({}, conversationDatas)
		},
		updateChatById(context,data) {//更新聊天数据
			var getKey=data.conversation_id?data.conversation_id:publicFc.getConversationId(data.userId);
            if(!context.state.chatDatalist[getKey])context.state.chatDatalist[getKey]={};
            context.state.chatDatalist[getKey].id=getKey;
            context.state.chatDatalist[getKey].list = data.data;
		},
		updateChatObjById(context,data) {//更新聊天数据对象
			var getKey=data.conversation_id?data.conversation_id:publicFc.getConversationId(data.userId);
            if(!context.state.chatDatalist[getKey])context.state.chatDatalist[getKey]={};
            context.state.chatDatalist[getKey].id=getKey;
            context.state.chatDatalist[getKey].list = data.data;
		},
		getChatList(context) {//获取聊天记录列表
			var data=publicFc.getKeyObjectStorage(context.state.userInfo.userId+'_'+'chatlistData')
			var sum=0;
			for(var i in data){
				sum+=data[i].num
			}
			context.state.chatListNum=sum
			context.commit('update_ChatList',data)
		},
		updateChatListInfoById(context,data) {//修改聊天列表
			var getKey = data.userId;
			var retdata = publicFc.getKeyObjectStorage(context.state.userInfo.userId+'_'+'chatlistData');
			if(data.data.windowType == 'GROUP'){
				if(typeof data.data.addGroupApply == 'undefined'){
					if(retdata[getKey].addGroupApply > 0){
						data.data.addGroupApply = retdata[getKey].addGroupApply;
					}
				}
			}
			retdata[getKey] = data.data;
			uni.setStorageSync(context.state.userInfo.userId+'_'+'chatlistData', JSON.stringify(retdata));
		},
		createChatObj(context,data){
			var userId=data.userId
			var windowType=data.windowType
            var key  = windowType=="GROUP"?"GROUP"+userId:userId;
			//初始化聊天记录
			var data2=publicFc.getKeyObjectStorage(context.state.userInfo.userId+'_'+'chatlistData')
			if(publicFc.is_empty(data2[key])){
				data2[key]=new Object();
			    uni.setStorageSync(context.state.userInfo.userId+'_'+'chatlistData', JSON.stringify(data2));
			}else{
                var info ={};
                if(windowType=="GROUP"){
                    info.groupInfo = data2[key];
                }else{
                    info.fromInfo = data2[key];
                }
				return {msg:'创建成功',data:info};
			}
			// 初始化聊天数据
            var data1=context.dispatch('getChatData')
            //console.log(data1);
			return new Promise(function(resolve, reject) {
				if(publicFc.is_empty(data1[userId])){
					switch (windowType){
						case 'SINGLE':
						http.request({
							url: '/friend/info/?id='+userId,
							complete:(res)=>{
								if (res.data.code == 200) {
									var detail=res.data.data
									data1[userId]={
										fromInfo:{
											nickName: detail.nickname,
											portrait: detail.portrait,
											userId: detail.uid,
											userType:detail.userType
										},
										groupInfo:{},
										list:[]
									}
                                    context.dispatch('updateChatData',data1)
									// 创建记录
									var msgList = {
										userId: detail.userId,
										personId: context.state.userInfo.userId,
										nickName: detail.nickName,
										portrait: detail.portrait,
										content: '',
										time: publicFc.getNewDate('format',true),
										num: 0,
										windowType: 'SINGLE',
										disturb:'N',//是否静默消息
										top:'N',//是否置顶
										userType:'normal'
									}
									context.dispatch('updateChatListInfoById', {
										userId: detail.userId,
										data: msgList
									});
									resolve({
										msg:'创建成功',
										data:data1[userId]
									})
								}else{
									reject({
										msg:'创建失败'
									});
								}
							}
						});
							break;
						case 'GROUP':
						http.request({
							url: '/group/getInfo/?id='+userId,
							complete:(res)=>{
								if (res.data.code == 200) {
									var detail=res.data.data;//console.log(detail);
									data1[userId]={
										fromInfo:{},
										groupInfo:{
											nickName: detail.name,
											portrait: JSON.stringify(detail.portrait),
											userId: detail.id,
										},
										list:[]
									}
                                    context.dispatch('updateChatData',data1)
									// 创建记录
									var msgList = {
										userId: detail.id,
										personId: context.state.userInfo.userId,
										nickName: detail.name,
										portrait: JSON.stringify(detail.portrait),
										content: '',
										time: publicFc.getNewDate('format',true),
										num: 0,
										windowType: 'GROUP',
										disturb:'N',//是否静默消息
										top:'N',//是否置顶
										userType:'GROUP'
									}
									context.dispatch('updateChatListInfoById', {
										userId: 'GROUP'+detail.id,
										data: msgList
									});
									resolve({
										msg:'创建成功',
										data:data1[userId]
									})
								}else{
									reject({
										msg:'创建失败'
									});
								}
							}
						});
							break;
						default:
							break;
					}
				}else{
					resolve({
						msg:'已存在',
						data:data1[userId]
					})
				}
			});
		},
		createChat(context,data){
			
		},
		clearUserinfo(context){
			context.commit('clear_Userinfo')
		},
		clearMsg(context){
			context.state.chatlist = {};
			context.state.chatDatalist = {};
			context.state.chatListNum = 0;
		},
		setCheckedshowstatus(context,show){
			context.state.chat_msg_list = {};
			context.state.chatCheckedShow = show;
		},
		setChatMsgList(context,list){
			context.state.chat_msg_list = list;
		},
		update_navigatorType(context,navigatorType){
			context.state.navigatorType = navigatorType;
		}
	}
})
export default store